<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Promise对象</title>
</head>
<body>
<script type="text/javascript">
    //先写一个传统的ajax
    // const xhr = new XMLHttpRequest();
    // xhr.onreadystatechange = function () {
    //     console.log(this.readyState);
    //     console.log(this.response);
    // }
    // xhr.open('GET','http://www.weather.com.cn/data/cityinfo/101010100.html',true);//这里存在跨域请求的问题
    // xhr.send();
    //promise封装


    function getJson(url) {
        const p = new Promise(((resolve, reject) => {
            const xhr = new XMLHttpRequest();
            xhr.onreadystatechange = function () {
                console.log(this.readyState);
                if (this.readyState === 4){
                    if (this.status === 200){
                        resolve(this.response);
                    }else{
                        reject('调用失败');
                    }
                }
            }
            xhr.open('GET',url,true);//这里存在跨域请求的问题
            xhr.send();
        }));
        return p ;
    }
    const pro = getJson('https://api.qweather.com/v7/weather/now?location=101010100&key=34256436546');
    pro.then((data)=>{
        console.log(data)
    }).catch((error)=>{
        console.log(error);
    });


</script>
</body>
</html>